<template>
  <div class="data-entry-container">
    <div v-if="isLoading" class="loading">
      <el-skeleton :rows="10" animated />
    </div>

    <div v-else>
      <!-- 当状态为未启动(0)时显示 -->
      <div v-if="reportWorkStatus === 0" class="no-work-started">
        <el-empty description="未开展体测上报工作" />
      </div>
      
      <!-- 当状态为已结束(2)时显示 -->
      <div v-else-if="reportWorkStatus === 2" class="work-finished">
        <el-empty description="体测上报工作已结束" />
      </div>
      
      <!-- 当状态为进行中(1)时显示 -->
      <div v-else-if="reportWorkStatus === 1" class="work-in-progress">
        <!-- 体测工作信息展示 -->
        <div class="report-work-info">
          <el-icon><Calendar /></el-icon>
          <span>{{ reportWorkInfo }}</span>
        </div>
        
        <!-- 主要内容区域 -->
        <div class="main-content">
          <!-- 筛选条件 -->
          <div class="filter-container">
            <el-row :gutter="20">
              <el-col :span="4">
                <el-select 
                  v-model="selectedStage" 
                  placeholder="学段选择" 
                  clearable
                  class="filter-select"
                  @change="handleStageChange"
                >
                  <el-option 
                    v-for="item in stageOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value" 
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select 
                  v-model="selectedGrade" 
                  placeholder="年级" 
                  clearable
                  class="filter-select"
                  :disabled="!selectedStage"
                  @change="handleGradeChange"
                >
                  <el-option 
                    v-for="item in gradeOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value" 
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select 
                  v-model="selectedClass" 
                  placeholder="班级" 
                  clearable
                  class="filter-select"
                  :disabled="!selectedGrade"
                  :loading="classLoading"
                  @change="handleClassChange"
                >
                  <el-option 
                    v-for="item in classOptions" 
                    :key="item.clazzId" 
                    :label="item.name" 
                    :value="item.clazzId" 
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button 
                  type="info" 
                  plain
                  class="reset-button"
                  @click="resetFilters"
                >
                  <el-icon><RefreshRight /></el-icon>
                  重置
                </el-button>
              </el-col>
              <el-col :span="4" :offset="4">
                <el-button type="primary">
                  <el-icon><Upload /></el-icon>
                  批量导入
                </el-button>
              </el-col>
            </el-row>
          </div>
          
          <!-- 数据表格 -->
          <div class="table-container">
            <el-table 
              :data="studentData" 
              border 
              stripe
              :cell-style="{ textAlign: 'center' }"
              :header-cell-style="{ backgroundColor: '#f5f7fa', textAlign: 'center' }"
              :border="false"
              class="custom-table"
              fit
              v-loading="tableLoading"
              max-height="450px"
            >
              <el-table-column prop="index" label="序号" width="80" align="center" />
              <el-table-column prop="studentName" label="姓名" width="120" align="center" />
              <el-table-column prop="studentCode" label="学号" width="140" align="center" />
              <el-table-column label="性别" width="80" align="center">
                <template #default="scope">
                  {{ scope.row.gender === 1 ? '男' : '女' }}
                </template>
              </el-table-column>
              <el-table-column label="状态" width="120" align="center">
                <template #default="scope">
                  <div class="status-capsule" :class="getStatusClass(scope.row.status)">
                    <div class="status-dot"></div>
                    <span>{{ getStatusText(scope.row.status) }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="totalScore" label="成绩" width="100" align="center" />
              <el-table-column label="评级" width="100" align="center">
                <template #default="scope">
                  <div class="rating-tag" :class="getRatingClass(scope.row.grade)">
                    {{ getRatingText(scope.row.grade) }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="年级" width="100" align="center">
                <template #default="scope">
                  {{ getGradeText(scope.row.gradeVal) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="180" align="center">
                <template #default="scope">
                  <div class="operation-buttons">
                    <el-button v-if="scope.row.status === 0 || scope.row.status === 2" 
                      type="primary" size="small" plain round
                      @click="openTestDataDialog(scope.row)">
                      <el-icon><Edit /></el-icon>
                      录入
                    </el-button>
                    <el-button v-if="scope.row.status === 1" 
                      type="warning" size="small" plain round
                      @click="openTestDataModifyDialog(scope.row)">
                      <el-icon><EditPen /></el-icon>
                      修改
                    </el-button>
                    <el-button type="danger" size="small" plain round>
                      <el-icon><Delete /></el-icon>
                      补录
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 分页 - 移到表格外部 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              background
              style="width: 100%;"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 体测数据录入对话框 -->
    <TestDataEntryDialog
      v-model:visible="testDataDialogVisible"
      :student-info="currentStudent"
      :is-modify="isModify"
      @refresh="refreshStudentList"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { Calendar, School, Upload, Edit, EditPen, Delete, RefreshRight } from '@element-plus/icons-vue';
import { getReportWorkOrganizationApi } from '../api/modules/reportWorkOrganization';
import { getClassListApi } from '../api/modules/class';
import { getStudentListApi, getStudentTestDataApi } from '../api/modules/student';
import { ElMessage } from 'element-plus';
import TestDataEntryDialog from '../components/TestDataEntryDialog.vue';

// 获取当前登录用户信息
const loginUser = ref(JSON.parse(localStorage.getItem('loginUser') || '{}'));
// 用户角色: 0: 班主任 1: 校管理员 2: 教育局管理员
const userRole = computed(() => loginUser.value?.role);
// 判断是否为班主任
const isClassTeacher = computed(() => userRole.value === 0);
// 判断是否为校管理员
const isSchoolAdmin = computed(() => userRole.value === 1);

// 加载状态
const isLoading = ref(true);

// 体测工作状态 0：未启动 1：进行中 2：已结束
const reportWorkStatus = ref(1); // 默认设为进行中用于展示

// 体测工作信息
const reportWorkData = ref({
  isStart: true,
  beginDate: '2025-09-01T00:00:00',
  endDate: '2025-10-01T00:00:00',
  status: 1
});

// 计算属性：体测工作信息文本
const reportWorkInfo = computed(() => {
  if (!reportWorkData.value) return '';
  
  const beginDate = new Date(reportWorkData.value.beginDate);
  const endDate = new Date(reportWorkData.value.endDate);
  
  const formatDate = (date) => {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  };
  
  let statusText = '';
  switch (reportWorkData.value.status) {
    case 0:
      statusText = '未启动';
      break;
    case 1:
      statusText = '进行中';
      break;
    case 2:
      statusText = '已结束';
      break;
    default:
      statusText = '未知状态';
  }
  
  return `${new Date().getFullYear()}年体测工作${statusText} · 有效时间${formatDate(beginDate)}-${formatDate(endDate)}`;
});

// 学段选项
const stageOptions = [
  { label: '小学', value: '0' },
  { label: '初中', value: '1' },
  { label: '高中', value: '2' }
];

// 筛选条件
const selectedStage = ref(null);
const selectedGrade = ref(null);
const selectedClass = ref(null);
const classLoading = ref(false);

// 年级选项（根据学段动态变化）
const gradeOptions = computed(() => {
  console.log('计算年级选项', selectedStage?.value);
  
  if (selectedStage === null) return [];
  
  const stageValue = selectedStage.value;
  console.log('学段值:', stageValue, typeof stageValue);
  
  if (stageValue === '0') { // 小学
    console.log('返回小学年级');
    return [
      { label: '一年级', value: 1 },
      { label: '二年级', value: 2 },
      { label: '三年级', value: 3 },
      { label: '四年级', value: 4 },
      { label: '五年级', value: 5 },
      { label: '六年级', value: 6 }
    ];
  } else if (stageValue === '1' || stageValue === '2') { // 初中或高中
    console.log('返回初中/高中年级');
    return [
      { label: '一年级', value: 1 },
      { label: '二年级', value: 2 },
      { label: '三年级', value: 3 }
    ];
  }
  return [];
});

// 班级选项
const classOptions = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 学生数据
const studentData = ref([]);
const tableLoading = ref(false);

// 体测数据录入对话框
const testDataDialogVisible = ref(false);
const currentStudent = ref({});
const isModify = ref(false);

// 打开体测数据录入对话框
const openTestDataDialog = (student) => {
  console.log('打开对话框的学生信息:', student);
  currentStudent.value = {
    studentId: student.id || student.studentId, // 确保studentId能够正确获取
    studentName: student.studentName,
    studentCode: student.studentCode,
    gender: student.gender,
    gradeVal: student.gradeVal // 添加年级值
  };
  console.log('处理后的学生信息:', currentStudent.value);
  isModify.value = false;
  testDataDialogVisible.value = true;
};

// 打开体测数据修改对话框
const openTestDataModifyDialog = async (student) => {
  console.log('打开修改对话框的学生信息:', student);
  currentStudent.value = {
    studentId: student.id || student.studentId,
    studentName: student.studentName,
    studentCode: student.studentCode,
    gender: student.gender,
    gradeVal: student.gradeVal
  };
  console.log('处理后的学生信息:', currentStudent.value);
  isModify.value = true;
  testDataDialogVisible.value = true;
};

// 刷新学生列表数据
const refreshStudentList = () => {
  fetchStudentList();
};

// 获取学生列表数据
const fetchStudentList = async () => {
  // 如果是校管理员并且未选择学段，不进行查询
  if (isSchoolAdmin.value && !selectedStage.value) {
    studentData.value = [];
    total.value = 0;
    return;
  }
  
  tableLoading.value = true;
  try {
    let params = {};
    
    if (isClassTeacher.value) {
      // 班主任不需要指定学段和年级，使用默认值
      params = {
        stage: 1,  // 默认值，保证后端验证通过
        grade: 1,  // 默认值，保证后端验证通过
        page: currentPage.value,
        pageSize: pageSize.value
      };
    } else {
      // 校管理员需要指定筛选条件
      params = {
        stage: parseInt(selectedStage.value),
        grade: selectedGrade.value || null,
        classId: selectedClass.value || null,
        page: currentPage.value,
        pageSize: pageSize.value
      };
    }
    
    console.log('获取学生列表参数', params, '用户角色:', userRole.value);
    
    const res = await getStudentListApi(params);
    if (res && res.code === 1 && res.data) {
      // 处理学生数据，添加序号
      studentData.value = res.data.records.map((item, index) => {
        return {
          ...item,
          index: (currentPage.value - 1) * pageSize.value + index + 1
        };
      });
      total.value = res.data.total;
    } else {
      studentData.value = [];
      total.value = 0;
      ElMessage.warning('获取学生数据失败');
    }
  } catch (error) {
    console.error('获取学生列表失败', error);
    ElMessage.error('获取学生列表失败');
    studentData.value = [];
    total.value = 0;
  } finally {
    tableLoading.value = false;
  }
};

// 分页方法
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchStudentList();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchStudentList();
};

// 处理筛选条件变化
const handleFiltersChange = () => {
  currentPage.value = 1; // 重置到第一页
  fetchStudentList();
};

// 处理学段变化
const handleStageChange = () => {
  console.log('学段变化前', selectedStage);
  console.log('学段值', selectedStage?.value, typeof selectedStage?.value);
  
  // 确保年级下拉框重置
  selectedGrade.value = null;
  selectedClass.value = null;
  classOptions.value = [];
  
  console.log('学段变化后', selectedStage?.value);
  
  // 重新获取学生列表
  handleFiltersChange();
};

// 处理年级变化
const handleGradeChange = async () => {
  selectedClass.value = null;
  if (selectedStage !== null && selectedGrade.value !== null) {
    await fetchClassList();
  } else {
    classOptions.value = [];
  }
  
  // 重新获取学生列表
  handleFiltersChange();
};

// 处理班级变化
const handleClassChange = () => {
  // 重新获取学生列表
  handleFiltersChange();
};

// 获取班级列表
const fetchClassList = async () => {
  if (selectedStage === null || selectedGrade.value === null) return;
  
  classLoading.value = true;
  try {
    const params = {
      stage: parseInt(selectedStage.value),
      grade: selectedGrade.value
    };
    
    console.log('获取班级列表参数', params);
    
    const res = await getClassListApi(params);
    if (res && res.code === 1 && res.data) {
      classOptions.value = res.data;
    } else {
      classOptions.value = [];
      ElMessage.warning('未获取到班级数据');
    }
  } catch (error) {
    console.error('获取班级列表失败', error);
    ElMessage.error('获取班级列表失败');
    classOptions.value = [];
  } finally {
    classLoading.value = false;
  }
};

// 重置筛选条件
const resetFilters = () => {
  selectedStage.value = null;
  selectedGrade.value = null;
  selectedClass.value = null;
  classOptions.value = [];
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 1: return 'success'; // 已录入
    case 0: return 'warning'; // 待录入
    case 2: return 'danger';  // 异常
    default: return 'info';
  }
};

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 1: return 'status-success'; // 已录入
    case 0: return 'status-warning'; // 待录入
    case 2: return 'status-danger';  // 异常
    default: return 'status-info';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1: return '已录入';
    case 0: return '待录入';
    case 2: return '异常';
    default: return '未知';
  }
};

// 获取评级文本
const getRatingText = (grade) => {
  if (grade === null || grade === undefined) return '未评';
  switch (grade) {
    case 0: return '优秀';
    case 1: return '良好';
    case 2: return '合格';
    case 3: return '不合格';
    default: return '未评';
  }
};

// 获取评级样式类
const getRatingClass = (grade) => {
  if (grade === null || grade === undefined) return 'rating-none';
  switch (grade) {
    case 0: return 'rating-excellent'; // 优秀
    case 1: return 'rating-good';      // 良好
    case 2: return 'rating-pass';      // 合格
    case 3: return 'rating-fail';      // 不合格
    default: return 'rating-none';
  }
};

// 获取年级文本
const getGradeText = (gradeVal) => {
  if (gradeVal === null || gradeVal === undefined) return '未知';
  
  // 数字转中文
  const numToChinese = (num) => {
    const chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
    return chineseNums[num] || num;
  };
  
  // 小学 1-6年级
  if (gradeVal >= 1 && gradeVal <= 6) {
    return `小学${numToChinese(gradeVal)}年级`;
  }
  // 初中 7-9年级
  else if (gradeVal >= 7 && gradeVal <= 9) {
    return `初中${numToChinese(gradeVal - 6)}年级`;
  }
  // 高中 10-12年级
  else if (gradeVal >= 10 && gradeVal <= 12) {
    return `高中${numToChinese(gradeVal - 9)}年级`;
  }
  // 大学 13-16年级
  else if (gradeVal >= 13 && gradeVal <= 16) {
    return `大学${numToChinese(gradeVal - 12)}年级`;
  }
  
  return `${gradeVal}年级`;
};

// 获取体测工作信息
const getReportWorkInfo = async () => {
  try {
    isLoading.value = true;
    const res = await getReportWorkOrganizationApi();
    if (res && res.code === 1 && res.data) {
      reportWorkData.value = res.data;
      reportWorkStatus.value = res.data.status;
      console.log('体测工作信息:', res.data);
    } else {
      ElMessage.warning('获取体测工作信息失败');
      // 设置默认值
      reportWorkStatus.value = 0; // 默认未启动
    }
  } catch (error) {
    ElMessage.error('获取体测工作信息失败');
    console.error('获取体测工作信息失败', error);
    // 设置默认值
    reportWorkStatus.value = 0; // 默认未启动
  } finally {
    isLoading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  // 调用接口获取体测工作信息
  getReportWorkInfo();
  
  // 如果体测工作进行中，获取学生数据
  if (reportWorkStatus.value === 1) {
    // 如果是班主任，直接获取学生列表
    // 如果是校管理员，等待用户选择筛选条件后再获取学生列表
    if (isClassTeacher.value) {
      fetchStudentList();
    }
  }
});

// 监听学段变化
watch(selectedStage, (newVal, oldVal) => {
  console.log('学段变化 watch', newVal, typeof newVal);
  if (newVal === '0') {
    console.log('选择了小学');
  } else if (newVal === '1') {
    console.log('选择了初中');
  } else if (newVal === '2') {
    console.log('选择了高中');
  } else {
    console.log('未选择学段');
  }
});
</script>

<style scoped>
.data-entry-container {
  padding: 20px;
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.loading {
  padding: 40px;
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.no-work-started,
.work-finished {
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
}

.work-in-progress {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.report-work-info {
  margin-bottom: 20px; /* 增加底部边距，弥补移除学校名称后的空间 */
  padding: 12px 15px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.report-work-info .el-icon {
  margin-right: 8px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 0 15px 15px;
  max-height: calc(100vh - 220px); /* 调整最大高度，因为移除了学校名称栏 */
  overflow: hidden;
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin-top: 15px;
  flex-shrink: 0; /* 防止过滤器区域被压缩 */
}

.filter-select {
  width: 100%;
}

.reset-button {
  width: 100%;
}

.table-container {
  margin-top: 15px;
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
  min-height: 200px;
  max-height: calc(100vh - 350px); /* 调整表格最大高度 */
}

/* 表格宽度控制 */
.custom-table {
  width: 100%;
  table-layout: fixed;
}

.pagination-container {
  margin-top: 20px;
  margin-bottom: 10px;
  padding: 15px 0;
  display: flex;
  justify-content: center;
  background-color: #f8f9fa;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  flex-shrink: 0; /* 防止分页条被压缩 */
  position: sticky; /* 使分页条固定在底部 */
  bottom: 0;
  z-index: 1;
  width: 100%; /* 确保宽度为100% */
}

.pagination-container :deep(.el-pagination) {
  justify-content: center; /* 分页组件内部元素居中 */
  width: 100%;
  display: flex;
  flex-wrap: wrap; /* 允许在小屏幕上换行 */
}

.pagination-container :deep(.el-pagination__total) {
  margin-right: 10px; /* 调整总数与其他元素的间距 */
}

.pagination-container :deep(.el-pagination__sizes) {
  margin-right: 10px; /* 调整每页条数选择器与其他元素的间距 */
}

.pagination-container :deep(.el-pagination__jump) {
  margin-left: 10px; /* 调整跳转框与其他元素的间距 */
}

/* 状态胶囊样式 */
.status-capsule {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
  width: 70px;
  height: 24px;
  border-radius: 12px; /* 设置为高度的一半 */
  margin: 0 auto; /* 居中显示 */
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

/* 已完成状态 */
.status-success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-success .status-dot {
  background-color: #67c23a;
}

/* 待录入状态 */
.status-warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-warning .status-dot {
  background-color: #e6a23c;
}

/* 异常状态 */
.status-danger {
  background-color: #fef0f0;
  color: #f56c6c;
}

.status-danger .status-dot {
  background-color: #f56c6c;
}

/* 评级标签样式 */
.rating-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

/* 优秀评级 */
.rating-excellent {
  background-color: #f0f9eb;
  color: #67c23a;
}

/* 良好评级 */
.rating-good {
  background-color: #e1f3d8;
  color: #67c23a;
}

/* 及格评级 */
.rating-pass {
  background-color: #fdf6ec;
  color: #e6a23c;
}

/* 不及格评级 */
.rating-fail {
  background-color: #fef0f0;
  color: #f56c6c;
}

/* 未评级 */
.rating-none {
  background-color: #f4f4f5;
  color: #909399;
}

/* 自定义表格样式 */
.custom-table :deep(td),
.custom-table :deep(th) {
  border-right: none !important; /* 移除纵向边框 */
  padding: 12px 0; /* 统一内边距 */
}

.custom-table :deep(.el-table__inner-wrapper) {
  border-left: none;
  border-right: none;
}

.custom-table :deep(.el-table__inner-wrapper::before) {
  display: none; /* 移除底部线 */
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap; /* 允许按钮换行 */
}

/* 确保操作按钮在小屏幕上也能正常显示 */
@media screen and (max-width: 1200px) {
  .operation-buttons {
    flex-direction: column;
    align-items: center;
    gap: 4px;
  }
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .main-content {
    max-height: calc(100vh - 180px); /* 调整响应式布局高度 */
  }
  
  .table-container {
    max-height: calc(100vh - 320px);
  }
  
  .pagination-container {
    padding: 10px 0;
  }
}

@media screen and (max-height: 800px) {
  .main-content {
    max-height: calc(100vh - 160px);
  }
  
  .table-container {
    max-height: calc(100vh - 300px);
  }
}
</style> 